package com.epam.training;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.epam.training.domain.Insurance;
import com.epam.training.service.insurance.InsuranceService;

@Controller
public class AddInsuranceController {
	private final InsuranceService service;

	@Autowired
	AddInsuranceController(InsuranceService service) {
		this.service = service;
	}

	@ModelAttribute
	private Insurance createInsurance(@RequestParam BigDecimal iPrice,
			@RequestParam String iName, @RequestParam String iDescription) {
		Insurance insurance = new Insurance();
		insurance.setName(iName);
		insurance.setPrice(iPrice);
		insurance.setDescription(iDescription);

		return insurance;
	}

	@RequestMapping(value = "/admin/addInsurance", method = RequestMethod.POST)
	private String addNewInsurance(@ModelAttribute Insurance insurance,
			Model model) {
		service.save(insurance);

		model.addAttribute("message", "insurence.added");

		return AdminPageController.ADMIN_PAGE;
	}

	@RequestMapping(value = "/admin/updateInsurance", method = RequestMethod.POST)
	private String updateInsurance(@ModelAttribute Insurance insurance,
			@RequestParam Integer insuranceId, Model model) {
		service.update(insurance, insuranceId);
		model.addAttribute("message", "insurence.update");

		return AdminPageController.ADMIN_PAGE;
	}

}
